//
// Created by 12992 on 24-10-1.
//

#include "media_packet.h"

#include <stdexcept>
#include <utility>
extern "C"
{
#include <libavcodec/avcodec.h>
}


namespace utils
{
    using namespace std;

    media_packet::media_packet(AVPacket* packet)
            : m_packet(av_packet_alloc())
    {
        if (!this->m_packet)
        {
            throw runtime_error("can not alloc packet in media_packet");
        }

        if (av_packet_ref(this->m_packet, packet) < 0)
        {
            throw runtime_error("can not ref packet!");
        }
    }

    media_packet::media_packet(media_packet&& packet) noexcept
            : m_packet(std::exchange(packet.m_packet, nullptr))
    {
    }

    media_packet::media_packet(const media_packet& packet)
            : m_packet(av_packet_alloc())
    {
        if (!this->m_packet)
        {
            throw runtime_error("can not alloc packet in media_packet");
        }

        if (av_packet_ref(this->m_packet, packet.m_packet) < 0)
        {
            throw runtime_error("can not ref packet!");
        }
    }

    media_packet& media_packet::operator=(const media_packet& packet)
    {
        auto copy_object = packet;
        swap(*this, copy_object);
        return *this;
    }

    media_packet& media_packet::operator=(media_packet&& packet) noexcept
    {
        this->m_packet = exchange(packet.m_packet, nullptr);
        return *this;
    }

    media_packet::~media_packet()
    {
        av_packet_free(&this->m_packet);
    }

    AVPacket* media_packet::get_packet()
    {
        return this->m_packet;
    }

    media_packet::operator bool() const noexcept
    {
        return this->m_packet;
    }
} // utils
